#include <ESP32PWM.h>

#define BLINKER_BLE
#include <Blinker.h>

BlinkerButton Button1("btn-abc");
BlinkerNumber Number1("num-abc");

int counter = 0;
int joyX = 0;
int joyY = 0;

const int servoPin = 21;
const int freq = 50;
const int resolution = 16;

   void button1_callback(const String & state)
   {
       BLINKER_LOG("get button state: ", state);
       digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));

       if (state == "press")
       {
           // 按下按钮，逐渐增加占空比使舵机转到 90 度位置
           for (int i = 1000; i <= 1500; i++)
           {
               ledcWrite(0, i);
               delay(10);
           }
       }
       else
       {
           // 释放按钮，逐渐减少占空比使舵机回到 0 度位置
           for (int i = 1500; i >= 1000; i--)
           {
               ledcWrite(0, i);
               delay(10);
           }
       }
   }

void dataRead(const String & data)
{
    BLINKER_LOG("Blinker readString: ", data);
    // 假设数据格式为 "x,y"
    int commaIndex = data.indexOf(',');
    if (commaIndex!= -1)
    {
        joyX = data.substring(0, commaIndex).toInt();
        joyY = data.substring(commaIndex + 1).toInt();
        BLINKER_LOG("Joy X: ", joyX);
        BLINKER_LOG("Joy Y: ", joyY);
    }
    counter++;
    Number1.print(counter);
}

void setup()
{
    Serial.begin(115200);
    BLINKER_DEBUG.stream(Serial);

    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);

    // 设置引脚为输出
    pinMode(servoPin, OUTPUT);

    // 配置通道 0，频率为 50Hz，分辨率为 16 位
    ledcSetup(0, freq, resolution);
    // 将通道 0 连接到引脚 21
    ledcAttachPin(servoPin, 0);

    Blinker.begin();
    Blinker.attachData(dataRead);

    Button1.attach(button1_callback);
}

void loop()
{
    Blinker.run();
}